if (typeof socket === 'undefined' || !socket.socket.connected) {
    if (typeof io === "undefined")
        console.log("Server offline");
    else
        var socket = io.connect('http://wextserv.nodejitsu.com:80');
}

function getIcons () {
    $("#icon-box").html("");
    socket.emit("getIcons");
}

function purchaseIcon (icon, dataTo_getIcons) {
    socket.emit("purchaseIcon", icon, dataTo_getIcons);
}

function getNotOwnedIcons (dataTo_getIcons) {
    socket.emit("getNotOwnedIcons", dataTo_getIcons);
}

function appendFavourites (data) {
    if (data.length > 0) { //
        $('#main-nav-favourites').html('');

        var k = 0;

        data.forEach(function (room) {
            $('#main-nav-favourites').append('<h3>' + (k + 1) + '. <a class="slideoutnav" id="' + room + '" href="#main-nav">#' + room + '</a></h3>' );
            k += 1;
        });
    } else {
        $("#main-nav-favourites").html("<h4>No favourite topics saved.</h4>");
    }
}

function updateBalance () {
    getNotOwnedIcons(JSON.parse($("#loginBox").data("dataStore")));
}

$(document).ready(function () {

    socket.on("err", function (errMsg) {
        alert(errMsg);
    });

    $("#main-nav").load("leftMenu.html");

    validateToken();
    socket.on("tokenValidated", function (data) {
        if (data !== 1) {
            appendFavourites(data.favourites);
            $("#loginBox").load("loggedInHeader.html", function () {
                
                $("#voteCount").html("Votes left to spend: " + data.voteCount + "/5");
                $('#email').append(data.email);
                $('#authlevel').append(data.authlevel);
                $('#email').css('color', 'white');
                $('#authlevel').css('color', 'white');
                $('#account-name').append(data.user + '.');
                $('#nameBox').html('<a href="profile.html?name=' + data.user + '" target="_blank">' + data.user + '</a>');
                getIcons();
                getNotOwnedIcons();
                $("#loginBox").data("dataStore", JSON.stringify(data)); //update votebalance in right-menu, move to survs?
            });
        } else {
            $("#account-login-header-box-nav").html("LOGIN");
            $("#loginContainer").load("login.html");
        }
    });
    
    socket.on('updatePopular', function (popularChats) {
        $('#main-nav-most-popular').html('');

        var k = 0;

        popularChats.forEach(function (popularChat) {
            $('#main-nav-most-popular').append('<h3>' + (k + 1) + '. <a class="slideoutnav" id="' + popularChat + '" href="#main-nav">' + popularChat + '</a></h3>');
            k += 1;
        });
    });

    socket.on('updateDiscover', function (data) {
        $('#main-nav-nearby').html('');

        var y = 0;
        data.list.forEach(function (discovered) {
            $('#main-nav-nearby').append('<h3>' + (y + 1) + '. <a class="slideoutnav" id="1' + discovered + '" href="#main-nav">' + discovered + '</a></h3>');
            y += 1;
        });
    });

    socket.on("updateFavourites", function (data) {
        appendFavourites(data);
    });
    
    socket.on("notOwnedIcons", function (data, dataTo_getIcons) {
        var icons = data.icons;

        $("#icon-box-nowned, #voteBalance").html("");

        $("#voteBalance").append("<h4>Vote balance: " + data.totalvotes + " <span onclick='updateBalance();' style='cursor: pointer;'>[UPDATE]</span></h4>");

        icons.forEach(function (icon) {
            $("#icon-box-nowned").append("<div class='iconContainer' id='iconPrice:" + icon.price + "'><img alt='prototype' src='bilder/icons/" + icon.name + ".png' class='icons' id='icon:" + icon.name + "' /></div>");
        });

        $("#icon-box-nowned > .iconContainer").on({
            mouseenter: function () {
                $("#icon-price").html("<h5>Icon price: " + $(this).attr("id").split(":")[1] + "</h5>");
                $(this).css({opacity: "1", filter: "alpha(opacity=100)"});
            }, mouseleave: function () {
                $("#icon-price").html("<h5>Icon price: (hover to display)</h5>");
                $(this).css({opacity: "0.4", filter: "alpha(opacity=40)"});
            }
        });

        $("#icon-box-nowned > .iconContainer").on("click", function () {
            purchaseIcon($(this).children(".icons").attr("id").split(":")[1], dataTo_getIcons);
        });
    });

    socket.on("ownedIcons", function (icons, currentIcon) { ///// INDEX OCH LOGGEDINHEADER
        icons.forEach(function (icon) {
            if (icon === currentIcon) {
                $("#icon-box").append("<div class='iconContainer' style='cursor: default; opacity: 1; filter: alpha(opacity=100);'><img alt='prototype' src='bilder/icons/" + icon + ".png' class='icons' id='icon:" + icon + "' /></div>");
            } else {
                $("#icon-box").append("<div class='iconContainer'><img alt='prototype' src='bilder/icons/" + icon + ".png' class='icons' id='icon:" + icon + "' /></div>");
            }
        });
    });

    socket.on("iconPurchased", function (dataTo_getIcons) {
        $("#icon-price").html("<h5>Icon price: (hover to display)</h5>");
        getIcons();
        getNotOwnedIcons(dataTo_getIcons);
    });
});